/*
 * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.liuxiany.alibaba.gateway.handler;

import cn.liuxiany.alibaba.common.request.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.handler.ResponseStatusExceptionHandler;
import reactor.core.publisher.Mono;

/**
 * 网关异常通用处理器，只作用在webflux 环境下 , 优先级低于 {@link ResponseStatusExceptionHandler} 执行
 * <p>
 * 只能捕获网关产生的异常，不能捕获下游服务的异常
 * URL匹配断言匹配失败(不管下游服务是否启动)可以捕获得到，下游服务的URL匹配失败则捕获不到
 * 比如断言为/consumer/** 那么请求是http://localhost:18080/consumer2/demo/test2/consumer2 则会捕捉到，httpstatus 为404
 * 当请求是http://localhost:18080/consumer2/demo222/test2/consumer2 则捕捉不到。此时则需要下游服务捕捉NoHandlerFoundException，需要下游服务throw-exception-if-no-handler-found设置为true.
 * 当下游服务不可达时（断言匹配成功，当时下游服务未启动），则会进入熔断器的fallback
 *
 * @author liuxiany
 * @date 2023/10/26
 */
@Slf4j
@Order(-1)
@RequiredArgsConstructor
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {

    private final ObjectMapper objectMapper;

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();

        if (response.isCommitted()) {
            return Mono.error(ex);
        }

        // header set
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        String message = null;
        int httpStatus = HttpStatus.INTERNAL_SERVER_ERROR.value();

        if (ex instanceof ResponseStatusException) {
            HttpStatus status = ((ResponseStatusException) ex).getStatus();
            response.setStatusCode(status);
            httpStatus = status.value();
        }

        if (httpStatus == HttpStatus.NOT_FOUND.value()) {
            message = "服务路径错误";
        } else {
            message = ex.getMessage();
        }

        final String finalMessage = message;

        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            try {
                log.warn("Error Spring Cloud Gateway, path is {}, message is {}", exchange.getRequest().getPath(), finalMessage);
                return bufferFactory.wrap(objectMapper.writeValueAsBytes(Result.failed(finalMessage)));
            } catch (JsonProcessingException e) {
                log.error("Error writing response", ex);
                return bufferFactory.wrap(new byte[0]);
            }
        }));
    }

}
